<template>
  <el-dialog
    append-to-body
    :title="'添加' + title + '账单'"
    :visible.sync="dialogFormVisible"
    width="500px"
    @close="close"
  >
    <el-form ref="form" label-width="80px" :model="form" :rules="rules">
      <el-form-item label="添加方式">
        <el-radio-group v-model="addtype">
          <el-radio :label="1">单笔添加</el-radio>
          <el-radio :label="2">批量添加</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="费用名称" prop="bill_title">
        <el-input v-model="form.bill_title" placeholder="请输入费用名称" />
      </el-form-item>
      <el-form-item label="账单金额" prop="bill_money">
        <el-input v-model="form.bill_money" placeholder="请输入账单金额" />
      </el-form-item>
      <el-form-item v-if="addtype == 1" label="日期" prop="bill_date">
        <el-date-picker
          v-model="form.bill_date"
          format="yyyy-MM-dd"
          placeholder="请选择记账日期"
          type="date"
          value-format="yyyy-MM-dd"
        />
      </el-form-item>
      <div v-else-if="addtype == 2" class="more">
        <div class="inline">
          <el-form-item label="日期" prop="start_date">
            <el-date-picker
              v-model="form.start_date"
              format="yyyy-MM-dd"
              placeholder="请选择开始日期"
              type="date"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <span class="daterange">--</span>
          <el-form-item label-width="0" prop="end_date">
            <el-date-picker
              v-model="form.end_date"
              format="yyyy-MM-dd"
              :picker-options="pickerOptions"
              placeholder="请选择结束日期"
              type="date"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
        </div>

        <el-form-item :label="title + '时间'">
          <el-select v-model="form.month" placeholder="请选择">
            <el-option
              v-for="item in 3"
              :key="item"
              :label="'每' + item + '月'"
              :value="item"
            />
          </el-select>
          <span class="daterange"></span>
          <el-select v-model="form.day" placeholder="请选择">
            <el-option
              v-for="item in 31"
              :key="item"
              :label="item + '号'"
              :value="item"
            />
          </el-select>
        </el-form-item>
      </div>
    </el-form>
    <div v-if="billList.length > 0" class="payDetail">
      <el-table :data="billList" max-height="250">
        <el-table-column label="费用名称" prop="bill_title" />
        <el-table-column label="金额" prop="bill_money">
          <template #default="{ row }">
            <div
              v-if="row.bill_type == 'income'"
              v-html="'+' + Number(row.bill_money).toFixed(2) + '元'"
            ></div>
            <div
              v-else-if="row.bill_type == 'payed'"
              v-html="'-' + Number(row.bill_money).toFixed(2) + '元'"
            ></div>
          </template>
        </el-table-column>
        <el-table-column :label="title + '日期'" prop="bill_date" />
        <el-table-column
          align="center"
          label="操作"
          show-overflow-tooltip
          width="85"
        >
          <template #default="{ row }">
            <el-button type="text" @click="payDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <template #footer>
      <el-button @click="createBill">生成账单</el-button>
      <el-button v-if="hasBill" type="primary" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { addMoreBill } from '@/api/bill'
  import { addMoreOwnerBill } from '@/api/ownerBill'
  import { parseTime } from '@/utils/index'
  export default {
    name: 'DoBill',
    data() {
      return {
        type: '',
        sn: '',
        owner_id: '',
        room_id: '',
        addtype: 1,
        hasBill: false,
        form: {
          bill_type: 'income',
          bill_title: '',
          bill_money: '',
          is_pay: '0',
          bill_date: parseTime(new Date(), '{y}-{m}-{d}'),
          start_date: parseTime(new Date(), '{y}-{m}-{d}'),
          end_date: '',
          month: 1,
          day: 1,
        },
        billList: [],
        rules: {
          bill_title: [
            { required: true, trigger: 'blur', message: '请输入费用名称' },
          ],
          bill_money: [
            { required: true, trigger: 'blur', message: '请输入账单金额' },
          ],
          bill_date: [
            { required: true, trigger: 'blur', message: '请选择记账日期' },
          ],
          start_date: [
            {
              required: true,
              message: '请选择开始日期',
              trigger: ['blur', 'change'],
            },
          ],
          end_date: [
            {
              required: true,
              message: '请选择结束日期',
              trigger: ['blur', 'change'],
            },
          ],
        },
        title: '',
        dialogFormVisible: false,
      }
    },
    computed: {
      pickerOptions() {
        let startDateVal = this.form.start_date
        return {
          disabledDate(time) {
            return time.getTime() < new Date(startDateVal).getTime()
          },
        }
      },
    },
    methods: {
      showEdit(type, e) {
        if (type == 'rent') {
          this.title = '待收'
          this.sn = e.rent_sn
          this.form.start_date = e.start_date
          this.form.end_date = e.end_date
          this.form.bill_type = 'income'
        } else if (type == 'owner') {
          this.title = '待付'
          this.owner_id = e.id
          this.room_id = e.room_id
          this.form.start_date = e.contract_start_date
          this.form.end_date = e.contract_end_date
          this.form.bill_type = 'payed'
        }
        this.type = type
        this.dialogFormVisible = true
        this.billList = []
        this.hasBill = false
      },
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.dialogFormVisible = false
      },
      payDelete(row) {
        this.billList.splice(this.billList.indexOf(row), 1)
        if (this.billList.length < 1) {
          this.hasBill = false
        }
      },
      createBill() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            let payData = this.form
            if (this.addtype == 1) {
              let tpl = {
                bill_type: payData.bill_type,
                bill_title: payData.bill_title,
                bill_money: payData.bill_money,
                is_pay: '0',
                bill_date: payData.bill_date,
              }
              this.billList.push(tpl)
              this.$refs['form'].resetFields()
              this.form = this.$options.data().form
              this.hasBill = true
            } else if (this.addtype == 2) {
              let dateList = this.getMonthBetween(
                payData.start_date,
                payData.end_date,
                payData.day
              )
              for (let i = 0; i < dateList.length; i++) {
                let tpl = {
                  bill_type: payData.bill_type,
                  bill_title: payData.bill_title,
                  bill_money: payData.bill_money,
                  is_pay: '0',
                  bill_date: dateList[i],
                }
                if (i % payData.month == 0) {
                  this.billList.push(tpl)
                }
              }
              this.$refs['form'].resetFields()
              this.form = this.$options.data().form
              this.hasBill = true
            }
          }
        })
      },
      async save() {
        var e = JSON.stringify(this.billList)
        if (this.type == 'rent') {
          let detail = {
            rent_sn: this.sn,
            bill_list: e,
          }
          const { data } = await addMoreBill(detail)
          if (data.is_success) {
            this.$baseMessage('添加成功', 'success', 'vab-hey-message-success')
            this.$emit('fetch-data')
            this.close()
          }
        } else if (this.type == 'owner') {
          let detail = {
            owner_id: this.owner_id,
            room_id: this.room_id,
            bill_list: e,
          }
          const { data } = await addMoreOwnerBill(detail)
          if (data.is_success) {
            this.$baseMessage('添加成功', 'success', 'vab-hey-message-success')
            this.$emit('fetch-data')
            this.close()
          }
        }
      },
      getMonthBetween(start, end, day) {
        let list = []
        var s = start.split('-')
        var e = end.split('-')
        var min = new Date()
        var max = new Date()
        min.setFullYear(s[0], s[1] * 1 - 1, s[2])
        max.setFullYear(e[0], e[1] * 1 - 1, e[2])
        var current = min
        while (current <= max) {
          var year = current.getFullYear()
          var month =
            current.getMonth() + 1 < 10
              ? '0' + (current.getMonth() + 1)
              : current.getMonth() + 1
          var lastDate = new Date(year, month, 0).getDate()
          var d = day < 10 ? '0' + day : day
          var dd = d < lastDate ? d : lastDate
          list.push(year + '-' + month + '-' + dd)
          current.setMonth(month)
        }
        return list
      },
    },
  }
</script>
<style lang="scss" scoped>
  .more {
    .inline {
      display: flex;
    }
    .el-input {
      width: 180px;
    }
    .el-select {
      width: 180px;
    }
    .daterange {
      display: inline-block;
      width: 20px;
      line-height: 32px;
      text-align: center;
    }
  }
</style>
